﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DataContexts.Supplier;

public partial class Supplier_Price_Default : System.Web.UI.Page
{
    private SupplierDataContext supplierContext = new SupplierDataContext();

    protected void Page_Load(object sender, EventArgs e)
    {
        ((BaseMasterPage)this.Master).CurrentPage = PageConfig.Pages.SupplierLocationDefault;
        if (!((BaseMasterPage)this.Master).AuthorizeCurrentUser())
            return;

        ltrMessage.Text = string.Empty;

        if (!IsPostBack)
        {
            LoadSuppliers();
            if (!UserAccess.IsCurrentUser(Enums.UserTypes.Admin))
            {
                ddlSuppliers.SelectedValue = UserAccess.CurrentSupplier.SupplierId.ToString();
                tdSupplierControl.Visible = false;
                tdSupplierHead.Visible = false;

                LoadLocations();

                gvSeasons.Visible = false;
                gvSuppSeasons.Visible = true;
                trPercentMargin.Visible = false;
                trActualMargin.Visible = false;
            }
            else
            {

                gvSeasons.Visible = true;
                gvSuppSeasons.Visible = false;
            }
        }
    }

    protected void ddlSuppliers_SelectedIndexChanged(object sender, EventArgs e)
    {
        LoadLocations();
    }
    protected void ddlLocations_SelectedIndexChanged(object sender, EventArgs e)
    {
        LoadVehicles();
    }
    protected void ddlVehicles_SelectedIndexChanged(object sender, EventArgs e)
    {
        pnlSeasonPrice.Visible = (ddlVehicles.SelectedIndex > 0);
        if (pnlSeasonPrice.Visible)
        {
            LoadSeasons();
            ClearAddFields();
        }
    }

    private void LoadSuppliers()
    {
        ddlSuppliers.DataSource = supplierContext.Suppliers;
        ddlSuppliers.DataTextField = "SupplierName";
        ddlSuppliers.DataValueField = "SupplierId";
        ddlSuppliers.DataBind();
        ddlSuppliers.Items.Insert(0, new ListItem("Select Supplier", "0"));

        ddlLocations.Items.Clear();
        ddlLocations.Items.Insert(0, new ListItem("Select Location", "0"));

        ddlVehicles.Items.Clear();
        ddlVehicles.Items.Insert(0, new ListItem("Select Vehicle", "0"));

        pnlSeasonPrice.Visible = false;
    }
    private void LoadLocations()
    {
        ddlLocations.DataSource = from sl in supplierContext.SupplierLocations
                                  join l in supplierContext.Locations on sl.LocationId equals l.LocationId
                                  where sl.SupplierId == Convert.ToInt32(ddlSuppliers.SelectedValue)
                                  select new { Text = l.LocationName + "-" + sl.City + "-" + sl.PostCode, Value = sl.SupplierLocationId };
        ddlLocations.DataTextField = "Text";
        ddlLocations.DataValueField = "Value";
        ddlLocations.DataBind();
        ddlLocations.Items.Insert(0, new ListItem("Select Location", "0"));

        ddlVehicles.Items.Clear();
        ddlVehicles.Items.Insert(0, new ListItem("Select Vehicle", "0"));

        pnlSeasonPrice.Visible = false;
    }
    private void LoadVehicles()
    {
        ddlVehicles.DataSource = from sv in supplierContext.SupplierVehicles
                                 join slv in supplierContext.SupplierLocationVehicles on sv.SupplierVehicleId equals slv.SupplierVehicleId
                                 where slv.SupplierLocationId == Convert.ToInt32(ddlLocations.SelectedValue)
                                 select new { Text = sv.VehicleCode + "-" + sv.VehicleDescription, Value = slv.SupplierLocationVehicleId };
        ddlVehicles.DataTextField = "Text";
        ddlVehicles.DataValueField = "Value";
        ddlVehicles.DataBind();
        ddlVehicles.Items.Insert(0, new ListItem("Select Vehicle", "0"));

        pnlSeasonPrice.Visible = false;
    }
    private void LoadSeasons()
    {
        if (gvSeasons.Visible)
            gvSeasons.DataSource = from sp in supplierContext.PriceOnSeasons
                                   where sp.SupplierLocationVehicleId == Convert.ToInt32(ddlVehicles.SelectedValue)
                                   orderby sp.StartDate
                                   select sp;
        if (gvSuppSeasons.Visible)
            gvSuppSeasons.DataSource = from sp in supplierContext.PriceOnSeasons
                                       where sp.SupplierLocationVehicleId == Convert.ToInt32(ddlVehicles.SelectedValue)
                                       orderby sp.StartDate
                                       select sp;
        gvSeasons.DataBind();
        gvSuppSeasons.DataBind();
    }
    private bool ValidDateRange(DateTime dtStart, DateTime dtEnd, int id)
    {
        bool rtnValue = true;

        List<PriceOnSeason> startData = (from sp in supplierContext.PriceOnSeasons
                                         where sp.SupplierLocationVehicleId == Convert.ToInt32(ddlVehicles.SelectedValue)
                                         && ((sp.StartDate >= dtStart && sp.EndDate <= dtStart) || (sp.StartDate >= dtEnd && sp.EndDate <= dtEnd))
                                         && sp.PriceOnSeasonId != id
                                         select sp).ToList();

        if (startData != null && startData.Count > 0)
        {
            rtnValue = false;
        }

        return rtnValue;
    }

    protected void gvSeasons_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            PriceOnSeason ps = e.Row.DataItem as PriceOnSeason;
            if (ps != null)
            {
                if ((e.Row.RowState & DataControlRowState.Edit) > 0)
                {
                    TextBox txtStartDateEdit = (TextBox)e.Row.FindControl("txtStartDateEdit");
                    TextBox txtEndDateEdit = (TextBox)e.Row.FindControl("txtEndDateEdit");
                    TextBox txtRentPriceEdit = (TextBox)e.Row.FindControl("txtRentPriceEdit");
                    TextBox txtPercentMarginEdit = (TextBox)e.Row.FindControl("txtPercentMarginEdit");
                    TextBox txtActualMarginEdit = (TextBox)e.Row.FindControl("txtActualMarginEdit");

                    txtStartDateEdit.Text = ps.StartDate.Value.ToString(Constants.DATE_FORMAT);
                    txtEndDateEdit.Text = ps.EndDate.Value.ToString(Constants.DATE_FORMAT);
                    txtRentPriceEdit.Text = ps.RentPrice.Value.ToString(Constants.DECIMAL_FORMAT);
                    if (ps.PercentMargin.HasValue)
                        txtPercentMarginEdit.Text = ps.PercentMargin.Value.ToString(Constants.DECIMAL_FORMAT);
                    if (ps.ActualMargin.HasValue)
                        txtActualMarginEdit.Text = ps.ActualMargin.Value.ToString(Constants.DECIMAL_FORMAT);


                }
                else if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate)
                {
                    Label lblStartDate = (Label)e.Row.FindControl("lblStartDate");
                    Label lblEndDate = (Label)e.Row.FindControl("lblEndDate");
                    Label lblRentPrice = (Label)e.Row.FindControl("lblRentPrice");
                    Label lblPercentMargin = (Label)e.Row.FindControl("lblPercentMargin");
                    Label lblActualMargin = (Label)e.Row.FindControl("lblActualMargin");

                    lblStartDate.Text = ps.StartDate.Value.ToString(Constants.DATE_FORMAT);
                    lblEndDate.Text = ps.EndDate.Value.ToString(Constants.DATE_FORMAT);
                    lblRentPrice.Text = ps.RentPrice.Value.ToString(Constants.DECIMAL_FORMAT);
                    if (ps.PercentMargin.HasValue)
                        lblPercentMargin.Text = ps.PercentMargin.Value.ToString(Constants.DECIMAL_FORMAT);
                    if (ps.ActualMargin.HasValue)
                        lblActualMargin.Text = ps.ActualMargin.Value.ToString(Constants.DECIMAL_FORMAT);

                    Helper.ApplyDeleteConfirmMsg(e, 6);
                }
            }


        }
    }
    protected void gvSeasons_RowDeleted(object sender, GridViewDeletedEventArgs e)
    {

    }
    protected void gvSeasons_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int id = Convert.ToInt32(gvSeasons.DataKeys[e.RowIndex].Value);
        PriceOnSeason ps = supplierContext.PriceOnSeasons.FirstOrDefault(p => p.PriceOnSeasonId == id);
        supplierContext.PriceOnSeasons.DeleteOnSubmit(ps);
        supplierContext.SubmitChanges();
        gvSeasons.EditIndex = -1;
        LoadSeasons();
    }
    protected void gvSeasons_RowEditing(object sender, GridViewEditEventArgs e)
    {
        ClearAddFields();
        gvSeasons.EditIndex = e.NewEditIndex;
        LoadSeasons();
    }
    protected void gvSeasons_RowUpdated(object sender, GridViewUpdatedEventArgs e)
    {

    }
    protected void gvSeasons_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        GridViewRow row = gvSeasons.Rows[Convert.ToInt32(e.RowIndex)];
        TextBox txtStartDateEdit = (TextBox)row.FindControl("txtStartDateEdit");
        TextBox txtEndDateEdit = (TextBox)row.FindControl("txtEndDateEdit");
        TextBox txtRentPriceEdit = (TextBox)row.FindControl("txtRentPriceEdit");
        TextBox txtPercentMarginEdit = (TextBox)row.FindControl("txtPercentMarginEdit");
        TextBox txtActualMarginEdit = (TextBox)row.FindControl("txtActualMarginEdit");

        int id = Convert.ToInt32(gvSeasons.DataKeys[e.RowIndex].Value);
        PriceOnSeason ps = supplierContext.PriceOnSeasons.FirstOrDefault(p => p.PriceOnSeasonId == id);

        if (ps != null)
        {
            ps.StartDate = Helper.DateFromString(txtStartDateEdit.Text);
            ps.EndDate = Helper.DateFromString(txtEndDateEdit.Text);
            ps.RentPrice = Convert.ToDecimal(txtRentPriceEdit.Text);
            ps.PercentMargin = Convert.ToDecimal(txtPercentMarginEdit.Text);
            ps.ActualMargin = Convert.ToDecimal(txtActualMarginEdit.Text);
            
            //ps.RentSellPrice = Convert.ToDecimal(txtRentSellPriceEdit.Text);
            ps.RentSellPrice = Helper.GetSellPrice(ps.RentPrice.Value, ps.ActualMargin.Value, ps.PercentMargin.Value);

            if (ValidDateRange(ps.StartDate.Value, ps.EndDate.Value, ps.PriceOnSeasonId))
            {
                supplierContext.SubmitChanges();
            }
            else
            {
                ltrMessage.Text = "The provided start and end date range are confictling existing seasons";
                return;
            }
        }

        ClearAddFields();
        gvSeasons.EditIndex = -1;
        LoadSeasons();
    }
    protected void gvSeasons_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        ClearAddFields();
        gvSeasons.EditIndex = -1;
        LoadSeasons();
    }
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        PriceOnSeason ps = new PriceOnSeason
        {
            SupplierLocationVehicleId = Convert.ToInt32(ddlVehicles.SelectedValue),
            StartDate = Helper.DateFromString(txtStartDateAdd.Text),
            EndDate = Helper.DateFromString(txtEndDateAdd.Text),
            RentPrice = Convert.ToDecimal(txtRentPriceAdd.Text),
            ActualMargin = !string.IsNullOrEmpty(txtActualMarginAdd.Text) ? Convert.ToDecimal(txtActualMarginAdd.Text) : 0,
            PercentMargin = !string.IsNullOrEmpty(txtPercentMarginAdd.Text) ? Convert.ToDecimal(txtPercentMarginAdd.Text) : 20
        };

        ps.RentSellPrice = Helper.GetSellPrice(ps.RentPrice.Value, ps.ActualMargin.Value, ps.PercentMargin.Value);

        //RentSellPrice = Convert.ToDecimal(txtRentSellPriceAdd.Text)
        if (ValidDateRange(ps.StartDate.Value, ps.EndDate.Value, 0))
        {
            supplierContext.PriceOnSeasons.InsertOnSubmit(ps);
            supplierContext.SubmitChanges();

            ClearAddFields();

            gvSeasons.EditIndex = -1;
            LoadSeasons();
        }
        else
        {
            ltrMessage.Text = "The provided start and end date range are confictling existing seasons";
        }
    }

    private void ClearAddFields()
    {
        txtStartDateAdd.Text = string.Empty;
        txtEndDateAdd.Text = string.Empty;
        txtRentPriceAdd.Text = string.Empty;
        txtActualMarginAdd.Text = string.Empty;
        txtPercentMarginAdd.Text = string.Empty;
    }

    #region Suppliers
    protected void gvSuppSeasons_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            PriceOnSeason ps = e.Row.DataItem as PriceOnSeason;
            if (ps != null)
            {
                if ((e.Row.RowState & DataControlRowState.Edit) > 0)
                {
                    TextBox txtStartDateEdit = (TextBox)e.Row.FindControl("txtStartDateEdit");
                    TextBox txtEndDateEdit = (TextBox)e.Row.FindControl("txtEndDateEdit");
                    TextBox txtRentPriceEdit = (TextBox)e.Row.FindControl("txtRentPriceEdit");
                    //TextBox txtPercentMarginEdit = (TextBox)e.Row.FindControl("txtPercentMarginEdit");
                    //TextBox txtActualMarginEdit = (TextBox)e.Row.FindControl("txtActualMarginEdit");

                    txtStartDateEdit.Text = ps.StartDate.Value.ToString(Constants.DATE_FORMAT);
                    txtEndDateEdit.Text = ps.EndDate.Value.ToString(Constants.DATE_FORMAT);
                    txtRentPriceEdit.Text = ps.RentPrice.Value.ToString(Constants.DECIMAL_FORMAT);
                    //if (ps.PercentMargin.HasValue)
                    //    txtPercentMarginEdit.Text = ps.PercentMargin.Value.ToString(Constants.DECIMAL_FORMAT);
                    //if (ps.ActualMargin.HasValue)
                    //    txtActualMarginEdit.Text = ps.ActualMargin.Value.ToString(Constants.DECIMAL_FORMAT);


                }
                else if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate)
                {
                    Label lblStartDate = (Label)e.Row.FindControl("lblStartDate");
                    Label lblEndDate = (Label)e.Row.FindControl("lblEndDate");
                    Label lblRentPrice = (Label)e.Row.FindControl("lblRentPrice");
                    //Label lblPercentMargin = (Label)e.Row.FindControl("lblPercentMargin");
                    //Label lblActualMargin = (Label)e.Row.FindControl("lblActualMargin");

                    lblStartDate.Text = ps.StartDate.Value.ToString(Constants.DATE_FORMAT);
                    lblEndDate.Text = ps.EndDate.Value.ToString(Constants.DATE_FORMAT);
                    lblRentPrice.Text = ps.RentPrice.Value.ToString(Constants.DECIMAL_FORMAT);
                    //if (ps.PercentMargin.HasValue)
                    //    lblPercentMargin.Text = ps.PercentMargin.Value.ToString(Constants.DECIMAL_FORMAT);
                    //if (ps.ActualMargin.HasValue)
                    //    lblActualMargin.Text = ps.ActualMargin.Value.ToString(Constants.DECIMAL_FORMAT);

                    Helper.ApplyDeleteConfirmMsg(e, 4);
                }
            }


        }
    }
    protected void gvSuppSeasons_RowDeleted(object sender, GridViewDeletedEventArgs e)
    {

    }
    protected void gvSuppSeasons_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int id = Convert.ToInt32(gvSuppSeasons.DataKeys[e.RowIndex].Value);
        PriceOnSeason ps = supplierContext.PriceOnSeasons.FirstOrDefault(p => p.PriceOnSeasonId == id);
        supplierContext.PriceOnSeasons.DeleteOnSubmit(ps);
        supplierContext.SubmitChanges();
        gvSuppSeasons.EditIndex = -1;
        LoadSeasons();
    }
    protected void gvSuppSeasons_RowEditing(object sender, GridViewEditEventArgs e)
    {
        ClearAddFields();
        gvSuppSeasons.EditIndex = e.NewEditIndex;
        LoadSeasons();
    }
    protected void gvSuppSeasons_RowUpdated(object sender, GridViewUpdatedEventArgs e)
    {

    }
    protected void gvSuppSeasons_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        GridViewRow row = gvSuppSeasons.Rows[Convert.ToInt32(e.RowIndex)];
        TextBox txtStartDateEdit = (TextBox)row.FindControl("txtStartDateEdit");
        TextBox txtEndDateEdit = (TextBox)row.FindControl("txtEndDateEdit");
        TextBox txtRentPriceEdit = (TextBox)row.FindControl("txtRentPriceEdit");
        //TextBox txtPercentMarginEdit = (TextBox)row.FindControl("txtPercentMarginEdit");
        //TextBox txtActualMarginEdit = (TextBox)row.FindControl("txtActualMarginEdit");

        int id = Convert.ToInt32(gvSuppSeasons.DataKeys[e.RowIndex].Value);
        PriceOnSeason ps = supplierContext.PriceOnSeasons.FirstOrDefault(p => p.PriceOnSeasonId == id);

        if (ps != null)
        {
            ps.StartDate = Helper.DateFromString(txtStartDateEdit.Text);
            ps.EndDate = Helper.DateFromString(txtEndDateEdit.Text);
            ps.RentPrice = Convert.ToDecimal(txtRentPriceEdit.Text);
            ps.RentSellPrice = Helper.GetSellPrice(ps.RentPrice.Value, ps.ActualMargin.Value, ps.PercentMargin.Value);
            //ps.PercentMargin = Convert.ToDecimal(txtPercentMarginEdit.Text);
            //ps.ActualMargin = Convert.ToDecimal(txtActualMarginEdit.Text);
            //ps.RentSellPrice = Convert.ToDecimal(txtRentSellPriceEdit.Text);
            if (ValidDateRange(ps.StartDate.Value, ps.EndDate.Value, ps.PriceOnSeasonId))
            {
                supplierContext.SubmitChanges();
            }
            else
            {
                ltrMessage.Text = "The provided start and end date range are confictling existing seasons";
                return;
            }
        }

        ClearAddFields();
        gvSuppSeasons.EditIndex = -1;
        LoadSeasons();
    }
    protected void gvSuppSeasons_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        ClearAddFields();
        gvSuppSeasons.EditIndex = -1;
        LoadSeasons();
    }
    #endregion
}
